// 云函数入口文件
const cloud = require('wx-server-sdk')
// var request = require('request')
var request = require('request-promise');

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  var url = ''
  var method = 'GET'
  var body1 = {}
  var contenttype = "application/json"
  if (event.method == 'getAccessToken') {
    url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=xxx&secret=xxx'
  } else if (event.method == 'getProductList') {
    url = 'https://api.weixin.qq.com/union/promoter/product/list?access_token=' + event.access_token + '&from=' + event.from + '&limit=' + event.limit
  } else if (event.method == 'getProductGenerate') {
    url = 'https://api.weixin.qq.com/union/promoter/product/generate?access_token=' + event.access_token,
      method = 'POST',
      body1 = {
        "pid": "xxx",
        "productList": event.productList
      },
      contenttype = "application/json"
  } else {
    url = ''
  }
  return new Promise((resolve, reject) => {
    request({
      url: url,
      method: method,
      json: true,
      headers: {
        "content-Type": contenttype,
      },
      body:body1,
    }, function (error, response, body) {
      try {
        resolve(body)
      } catch (e) {
        reject()
      }
    })
  })
}